
/**
 * 满意度调查问卷
 */
    define(['jquery'],function($){
				
		var rootid = 'question-main-page'
		var _container = $('#'+rootid + ' .problem-container')	
		var _nextPageBtn = $('#'+rootid + ' #bt_next')
		var _prePageBtn = $('#'+rootid + ' #bt_prev')
		var _submitBtn =  $('#'+rootid + ' #bt_sub')
		var page = 1;
		var per_page_num = 6;
		var userInfo = {};
		var problem;
		
		//定时器变量
		var t;
		
		//页面定时器变量
		var baseCount=59,pageCount;
	
		//操作完成定时器
		var finishiCnt ,finishBase = 5;
		
		//页面定时器dom对象
		var pageClockEl;
		
		//页面操作完成定时器dom对象
		var finishEl;
		//选择记录
		var _data = [];
		var btnEvent = {
				/**
				 * 翻页
				 * 
				 * @param _options.type
				 *            翻页类型
				 */
				pageMove:function(_options){
					if(_options && _options.type=='back'){
						page -= 1;
					}else{
						page += 1;
					}				
					var _htmlCode = private_method.getPageProblemHtml(page);
					private_method.showPageProblemHtml(_htmlCode);
				},
		
				nextPage:function() {
					btnEvent.pageMove({type:'nextPage'})
					//定时器重置
					pageCount = baseCount;
				},
				
				previousPage:function() {
					btnEvent.pageMove({type:'back'})
					//定时器重置
					pageCount = baseCount;
				},
				
				imgClick:function() {
									
					var selectScore = $(this).children('img').attr('value');
					var brothers = $(this).siblings();
					var problemCode = $(this).parent().attr('code');
					for (var i = 0; i < brothers.length; i++) {
						var brother = brothers[i];
						$(brother).css("background-color", "white")
					}
					$(this).css("background-color", "red");
					var problemSubject;
					for (var i = 0; i < problem.length; i++) {
						if (problem[i].problem_code == problemCode) {
							problemSubject = problem[i].problem_subject;
							break;
						}
					}
					
					var oneResult = {
							problem_code 	: problemCode,
							problem_subject : problemSubject, 
							evaluate_type	: userInfo.type,
							score 			: selectScore
					}
					
					for (var i = 0; i < _data.length; i++) {
						if (_data[i].problem_code == problemCode) {
							_data.splice(i, 1);
							break;
						}
					}
					_data.push(oneResult);
					//window.console($(this).val() + ' ' + 	this.parentElement.code);
					//定时器重置
					pageCount = baseCount;
					
					
					//是否启用下一页或者提交按钮
					if (_data.length == problem.length) {
						_submitBtn.attr('src', '../images/questionary/bt_3.png');
						_submitBtn.unbind('click');
						_submitBtn.bind('click', btnEvent.save)
					}
					
					if (_data.length >= page * per_page_num) {
						_nextPageBtn.attr('src', '../images/questionary/bt_2.png');
						_nextPageBtn.unbind('click');
						_nextPageBtn.bind('click', btnEvent.nextPage)
					}
					
				},
				
				save:function() {
					if(_data){
						var _url = '/portal/saveEvaluateResult';
						$.ajax({
						 	url:_url,
						 	type : 'post',
				 			dataType:'json',
				 			data:$.toJSON({userid:userInfo.patient_no,dataList:$.toJSON(_data),type:userInfo.type}),
				 			contentType:'appliction/json;charset=utf-8',						
				 			success:function(data){
				
				 			//清除题目和按钮
				 			_container.empty()
				 			_nextPageBtn.css('display','none')
				 			_prePageBtn.css('display', 'none')
				 			_submitBtn.css('display', 'none')
				 			var _h = 
										'<div>'+
								           
								           ' <h2 id="h2text">非常感谢您对我们医院的支持！</h2>'+
								            '<p style="text-align: center;font-size: 20px;"><span id="sptext">您的评价是对我们最大的帮助。</span>'+
								             '<span id="finish-clock"></span>'+
								            '</p>'+
								        '</div>'
	
								    
						
				 			_container.append(_h);
				 			private_method.pageClose({count:5,target:'finish-clock'})
				 			},
				 			error:function(err,err1,err2){
				 				if(window.console){
				 					console.log('save failure ...');
				 				}
				 			}
					 	})
					}	
				}
			};
		
		
		var private_method = {
			
			/**
			 * @param _options.code
			 *            问卷题目
			 * 
			 */
			getProblemHtml:function(_options){
				var _html = '<td class="problem_option" group="problem" code="'+_options.problem_code+ '" height="86px" width="45%">' +
                              '<div class="div_tp">非常满意<img value="5" src="../images/questionary/tb_1.png" width="60" height="59"></div>'+
                              '<div class="div_tp">满意<img value="4" src="../images/questionary/tb_2.png" width="60" height="59"></div>'+
                              '<div class="div_tp">基本满意<img value="3" src="../images/questionary/tb_3.png" width="60" height="59"></div>'+
                              '<div class="div_tp">不太满意<img value="2" src="../images/questionary/tb_4.png" width="60" height="59"></div>'+
                              '<div class="div_tp">不满意<img value="1" src="../images/questionary/tb_5.png" width="60" height="59"></div></td>'+
                              '<td width="5%"></td> '
                return _html
			}
			
			,
			
			showPageProblemHtml:function(_htmlCode) {
				_container.empty();
				_container.append(_htmlCode);	
				var isHasNextPageBtn = false;
				//翻页显示
				if (_data) {
					for (var i = 0; i < _data.length; i++) {
						var divs = $('#'+rootid + ' .problem-container .problem_option[code="'
									+ _data[i].problem_code+ '"]' + ' .div_tp');
						var imgs = $(divs).children('img');
						for (var j = 0; j < imgs.length; j++) {
							if (imgs[j].attributes['value'].value == _data[i].score) {
								isHasNextPageBtn = true;
								divs[j].style.backgroundColor='red';
							}
						}
					}
					
					if (isHasNextPageBtn) {
						_nextPageBtn.attr('src', '../images/questionary/bt_2.png');
						_nextPageBtn.unbind('click');
						_nextPageBtn.bind('click', btnEvent.nextPage)
					}
					if (_data.length == problem.length) {
						_submitBtn.attr('src', '../images/questionary/bt_3.png');
						_submitBtn.unbind('click');
						_submitBtn.bind('click', btnEvent.save)
					}
				}
				$('.div_tp').unbind('click');
				$('.div_tp').bind('click', btnEvent.imgClick);
			},
			
			/**
			 * 获取当页所有问卷题目
			 * 
			 * @param _optons.page
			 *            问卷页号
			 * @param _options.problem
			 *            问卷题目集合
			 */
			getPageProblemHtml:function(_options){				
				_nextPageBtn.css('display','none')
				_prePageBtn.css('display', 'none')
				_submitBtn.css('display', 'none')
				// 绑定点击事件
				var _df = {
					page: 1,
					problem: problem
				}
				var _default = $.extend({},_df,_options)
				if(_default.problem && _default.problem.length){
					var _cnt = _default.problem.length;
					// 当前页问卷起始题目
					var _start = (page -1) *6
					// 当前页问卷结束题目
					var _end = page * 6 ;

					// 有上一页按钮
					if (_start && _start != 0) {
						_prePageBtn.css('display', 'inline')
						_prePageBtn.unbind('click')
						_prePageBtn.bind('click', btnEvent.previousPage)
					}
					// 有下一页按钮，但不启用
					if (_end && _end < _cnt) {
						_nextPageBtn.attr('src', '../images/questionary/bt_21.jpg')
						_nextPageBtn.css('display','inline')
						_nextPageBtn.unbind('click')
					}
					
					//有提交按钮，但是不启用
					if(_end &&　_end >= _cnt){						
						_end = _cnt;
						_submitBtn.attr('src', '../images/questionary/bt_31.jpg');
						_submitBtn.css('display', 'inline')
						_submitBtn.unbind('click')
					}
					
					var _rowHtml = '';
					var _allHtml = '';
					for(var i=_start; i<_end; i++){						
						var _p = _default.problem[i];					
						var _text = (i+1) +'、' + _p.problem_subject;
						_rowHtml +='<td height="40" align="left" class="wenjuan_bt" valign="top" title="'+_p.problem_code +'"> '+_text+'</td>'
                            
						if((i%2)==1 ){
							
							_allHtml += '<table width="100%" border="0" cellspacing="0" cellpadding="0" group="row_1" style="display: table;">' +
				                          '<tbody>'+
				                          '<tr>' +	 
											_rowHtml +
										'</tr>'+
                          
				                          '<tr>'+
				                          
				                          private_method.getProblemHtml(_default.problem[i-1]) + 
				                          private_method.getProblemHtml(_p) +			          
				                          '</tr>'+
				                          '<tr>'+
				                          '<td height="10"></td>'+
				                          '</tr>'+
				                        '</tbody></table>'
							
							// 清除行数据
							_rowHtml = '';
						}else{
							// 第一行后面增加一栏，以便对齐
							_rowHtml += '<td></td>'

							if (i == _end-1) {
								_allHtml += '<table width="100%" border="0" cellspacing="0" cellpadding="0" group="row_1" style="display: table;">' +
		                          '<tbody>'+
		                          '<tr>' +	 
									_rowHtml +
								'</tr>'+
                
		                          '<tr>'+
		                          private_method.getProblemHtml(_p) +                          	
		                          	 '<td></td>'+
		                            
		                          '</tr>'+
		                          '<tr>'+
		                          '<td height="10"></td>'+
		                          '</tr>'+
		                        '</tbody></table>'
							}
						}
						
					}
					
					_allHtml = '<tbody><tr><td> '+
									_allHtml	+
								'</td></tr></tbody>'
								
					return _allHtml;
				}
				
			}
			
			
			,
			/**
			 * 获取问卷题目
			 * 
			 * @param _options.type
			 *            问卷类型
			 * @param _options.patientCode
			 *            患者编码
			 */
			getProblem:function(_options){	
				if(!problem){
					// 获取用户及题目信息
					var _url
					if(_options.type ==1 ){
						_url = '/portal/getOutpatientQueDomain';
					}else{
						_url = '/portal/getInpatientQueListDomain'
					}
					var _param = {
						url:_url,
						type : 'post',
			 			dataType:'json',
			 			contentType:'appliction/json;charset=utf-8',	
						async: false,
						success:function(data){
							if(data && data.rows){
								problem = data.rows
							}
						}
						,
						failure:function(){
							
						}
					}
					$.ajax(_param)
				}
				return problem;
			}
			
			,
			/**
			 * * 获取用户信息
			 * 
			 * 
			 */
			
			getUserInfo:function(){
				// 获取页面参数
				var ret = {} , retVal
				var _param = window.location.search
				
				if(_param){
					_param = _param.substring(1);
				}
				var _parray = _param.split('&');
				if(_parray.length>0){
					for(var i=0;i<_parray.length;i++){
						var _p = _parray[i];
						if(_p){
							
							var _array = _p.split('=');
							if(_array.length=2){
								if(_array[0]){								
									ret[_array[0]]=_array[1]																	
								}									
							}
						}						
					}
				}	
				var _url = '/portal/'
				if(ret && ret.type){
					if(ret.type=='1' || ret.type==1){
						// 门诊
						_url = '/portal/getOutpateintInfo'
					}else{
						_url = '/portal/getInpateintInfo'
					}
				}
				
				$.ajax({
					url:_url,
					async:false,
					data:{patient_no:ret.patientCode},
					success:function(data){
						if(data){
							retVal = data
							retVal.type = ret.type
						}
					}
					,
					failure:function(){
					
					}
				})
				return retVal;
			}
			,
			/**
			 * 设定页面关闭倒计时			 
			 * @param _options.target	倒计时dom元素
			 */
			pageClose:function(_options){
				var _df = {					
					target:'page-clock'
				}
				if(t){
					clearTimeout(t);
				}
				var _default = $.extend({},_df,_options);				
				
				if(_default.target=='finish-clock'){
					private_method.setFinishTimedout();
				}else{
					private_method.setPageTimeout();
				}
				
			}
			,
			/**
			 * @param _options.count	倒计时时长
			 * @param _options.target	倒计时dom元素
			 */
			setPageTimeout:function(){	
				 
				
				pageClockEl = !pageClockEl?$('#'+rootid + ' #page-clock'):pageClockEl							
				
				if(pageCount){					
					pageClockEl.html(pageCount);
					pageCount -=1;
					t=setTimeout(private_method.setPageTimeout,1000);
				}else{
					if(t){
						clearTimeout(t);
					}	
					window.opener=null;
					window.open('','_self');
					window.close();
				}
			}
			,
			setFinishTimedout:function(){
				
				if(t){
						clearTimeout(t);
					}	
				finishEl = !finishEl?$('#'+rootid + ' #finish-clock'):finishEl
				if(finishiCnt){
					finishEl.html(finishiCnt);
					finishiCnt -=1;
					t=setTimeout(private_method.setFinishTimedout,1000);
				}else{
					window.opener=null;
					window.open('','_self');
					window.close();
				}
			}
			
		}
		
		var public_method = {
			init:function(){
				// 清理遗留数据
				userInfo = null;
				problem = null;
				_data = [];
				page = 1;
				if(window.console){
					console.log('init fired ...')
				}
				userInfo = private_method.getUserInfo()		
				if(userInfo){
					var _no
					if(userInfo.type==1){
						_no = userInfo.outpatient_number
					}else{
						_no = userInfo.zyhm
					}
					var _el = $('#'+rootid + ' #patient-info')
					_el.html(userInfo.patient_name + '，您这次的门诊号（或）住院号为' + _no +'，请您对医院的服务进行评价。')
				}else{
					var _el = $('#'+rootid + ' #patient-info')
					_el.html('您的就诊卡无效或输入的住院号无效或本次就诊记录已经评价，页面将会在<span id="finish-clock"></span>秒钟后关闭窗口。')
					finishiCnt = finishBase;
					private_method.pageClose({target:'finish-clock'})
					return;
				}
				// 获取problem
				private_method.getProblem(userInfo)
				// 根据当前页号生成html
				var _htmlCode = private_method.getPageProblemHtml()			
				private_method.showPageProblemHtml(_htmlCode)
				
				//初始化页面定时器
				finishiCnt = finishBase;
				pageCount = baseCount;
				private_method.pageClose();
			}
		}
		return public_method;
	});	

